package edu.hda.pt.server.connections.netty;

import java.util.Vector;

import org.jboss.netty.channel.Channel;

/**
 * Thread for managing the streams
 * 
 * @author Marc Hammerton
 * 
 */
public class StreamThread extends Thread {

	private Vector<Channel> channels = new Vector<Channel>();
	private int fileSize = 0;

	/**
	 * Sets the file size which should be sent to the client
	 * 
	 * @param fileSize
	 *            - the fileSize to set
	 */
	public void setFileSize(int fileSize) {
		this.fileSize = fileSize;
	}

	/**
	 * Returns the file size
	 * 
	 * @return the file size
	 */
	public int getFileSize() {
		return fileSize;
	}

	/**
	 * Adds a new channel
	 * 
	 * @param channel
	 *            - the channel to be added
	 */
	public void addChannel(Channel channel) {
		this.channels.add(channel);
	}

	/**
	 * Removes an existing channel
	 * 
	 * @param channel
	 *            - the channel to be removed
	 */
	public void removeChannel(Channel channel) {
		this.channels.remove(channel);
	}

	/**
	 * While the thread is not interrupted, it checks if a channel exists. In
	 * this case, it sends a message of the size fileSize to the client. If no
	 * channel exists, it waits until it is notified.
	 */
	@Override
	public void run() {

		while (!isInterrupted()) {
			if (channels.size() == 0) {
				this.fileSize = 0;
				try {
					synchronized (this) {
						this.wait();
					}

				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			} else {
				byte[] data = new byte[this.fileSize];
				synchronized (channels) {
					for (Channel channel : channels) {
						if (channel.isOpen()) {
							if (channel.isWritable())
								channel.write(data);
						} else {
							interrupt();
						}
					}
				}
			}
		}
	}

	/**
	 * @see java.lang.Thread#interrupt()
	 */
	@Override
	public void interrupt() {
		super.interrupt();
	}
}
